<template>
  <div>
    <div class="top">
      <div class="top-op">
        <div class="search-panel">
          <el-input clearable placeholder="输入文件名搜索" v-model="searchQuery" @keyup.enter="searchFiles">
            <template #suffix>
              <i class="iconfont icon-search" @click="searchFiles"></i>
            </template>
          </el-input>
        </div>&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button @click="delFileBatch" type="danger" :disabled="selectedFileIds.length === 0">
          <span class="iconfont icon-del"></span>
          批量删除
        </el-button>
      </div>
      <Navigation ref="navigationRef" @navChange="navigateFolder"></Navigation>
    </div>

    <div class="breadcrumb">
      <span v-for="(item, index) in breadcrumb" :key="item.fileId">
        <a @click="navigateToFolder(item.fileId)">{{ item.fileName }}</a>
        <span v-if="index < breadcrumb.length - 1"> / </span>
      </span>
    </div>

    <div class="file-list" v-if="files.length > 0">
      <el-table ref="tableRef" :data="files" style="width: 100%" stripe @selection-change="onRowSelected">
        <el-table-column type="selection" width="50"></el-table-column>

        <el-table-column label="文件名" prop="fileName" width="150" align="center">
          <template #default="{ row }">
            <div class="file-item" @click="handleFileClick(row)">
              <icon :fileType="formatFileType(row.fileType)"></icon>
              <span class="file-name" :title="row.fileName">{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label=" " width="700" align="center">
          <template #default="{ row }">
            <div class="file-item">
              <div class="edit-panel">
                <span class="iconfont icon-download" @click.stop="downloadFile(row)"></span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100px">
          <!-- 通过作用域插槽给子组件传入内容，通过v-slot获取子组件传过来的数据，解构赋值给user -->
          <template v-slot="{ row }">
            <el-switch v-model="row.isDelete" :active-value="true" :inactive-value="false"
              style="--el-switch-on-color: #f56c6c;" @click="handleStatusChange(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="时间" prop="uploadTime" width="200" align="center">
          <template #default="{ row }">
            <span>{{ row.uploadTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="大小" prop="fileSize" width="auto" align="center">
          <template #default="{ row }">
            <span v-if="!row.is_folder">{{ formatFileSize(row.fileSize) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="no-data" v-else>
      <div class="no-data-inner">
        <Icon iconName="no_data" :width="120" fit="fill"></Icon>
        <div class="tips">当前目录为空</div>
      </div>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, inject } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElLoading } from 'element-plus'
// 当前目录 ID 和面包屑导航
const currentFolderId = ref(0);
const breadcrumb = ref([{ fileName: "根目录", fileId: 0 }]);

// 文件列表和搜索内容
const files = ref([]);
const searchQuery = ref("");
const selectedFileIds = ref([]);
//axios
let $http = inject('$http');
//查询用户的id
const route = useRoute();
let userId = route.query.userId;
//查询参数
const queryParams = ref({
  userId: userId,
})
// 加载目录内容
const loadFolderContents = (folderId) => {
  console.log("userId" + userId)
  if (folderId !== null) {
    queryParams.value.folderId = folderId
  } else {
    queryParams.value.folderId = null
  }
  $http({
    method: 'post',
    url: '/files/searchFilesById',
    data: queryParams.value
  }).then(response => {
    files.value = response.data.data
    files.value.sort((a, b) => {
        if (a.isFolder && !b.isFolder) {
          return -1; // 文件夹在前
        } else if (!a.isFolder && b.isFolder) {
          return 1; // 文件在后
        } else {
          return a.fileName.localeCompare(b.fileName); // 按文件名排序
        }
      });


  })
  // const result = mockFiles.filter(file => file.parent_id === folderId);
  // files.value = result;
  console.log("Loaded files:", files.value);  // 调试输出
};
//修改文件夹是否删除状态
const handleStatusChange = function (file) {
  console.log("修改文件夹是否删除状态", file.isDelete)
  $http({
    method: 'post',
    url: '/files/updateFilesIsDelete',
    data: file
  }).then(response => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
    } else {
      ElMessage.error(response.data.msg)
    }
  })
}
onMounted(() => {
  loadFolderContents(currentFolderId.value);
  console.log("Files after loading:", files.value);  // 确认 files 是否正确
});

// 处理文件点击
const handleFileClick = (file) => {
  console.log("Navigating to folder:", file.fileId);
  if (file.isFolder) {
    console.log("Navigating to folder:", file.fileId)
    currentFolderId.value = file.fileId;
    breadcrumb.value.push({ fileName: file.fileName, fileId: file.fileId });
    loadFolderContents(file.fileId);
  }
};

// 面包屑导航跳转
const navigateToFolder = (folderId) => {
  console.log("Navigating to folder:", folderId);
  const index = breadcrumb.value.findIndex(item => item.fileId === folderId);
  breadcrumb.value = breadcrumb.value.slice(0, index + 1);
  currentFolderId.value = folderId;
  loadFolderContents(folderId);
};

// 搜索文件
const searchFiles = () => {
  if (searchQuery.value === "") {
    return;
  }
  queryParams.value.searchQuery = searchQuery.value
  loadFolderContents();
  queryParams.value.searchQuery = ""
};

// 格式化文件大小
const formatFileSize = (size) => {
  if(size > 1024*1024){
    size = (size/1024/1024).toFixed(2) + 'MB'
        }
        else if(size == 0 || size == null){
          size = ' '
        }
        else{
          size = (size/1024).toFixed(2) + 'KB'
        }
  return size;
};
const fileTypeMap = {
  文件夹: { desc: "目录", icon: "folder" },
  MP4文件: { desc: "视频", icon: "video" },
  MP3文件: { desc: "音频", icon: "music" },
  JPG文件: { desc: "图片", icon: "image" },
  PNG文件: { desc: "图片", icon: "image" },
  EXE文件: { desc: "exe", icon: "exe" },
  DOC文件: { desc: "doc", icon: "word" },
  EXCEL文件: { desc: "excel", icon: "excel" },
  TXT文件: { desc: "纯文本", icon: "txt" },
  CODE文件: { desc: "程序", icon: "code" },
  ZIP文件: { desc: "压缩包", icon: "zip" },
  其他文件: { desc: "其他文件", icon: "others" },
};
const formatFileType = (fileType) => {
  if (fileTypeMap[fileType]) {
    return fileType
  } else {
    return "其他文件"
  }
}
// 获取当前路径
// const getCurrentPath = () => {
//   return breadcrumb.value.map(item => item.fileName).join('/');
// };

// 多选
const onRowSelected = (rows) => {
  console.log("Selected rows:", rows);
  selectedFileIds.value = rows.map(row => row.fileId);
};

// 删除文件
const delFileBatch = () => {
  // TODO: 实现批量删除逻辑
  console.log("Deleting files:", selectedFileIds.value);
  $http({
    method: 'post',
    url: '/files/deleteFiles',
    data: "deleteIds=" + selectedFileIds.value,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }).then(response => {
    ElMessage.success(response.data.msg)
  })

};

// 下载文件
const downloadFile = (file) => {
  if (file.isFolder) {
    downloadFolder(file);
  } else {
    downloadAFile(file)
  }
};
const downloadFolder = (file) => {
  // 显示“下载中”的弹窗
  // 创建一个 AbortController 实例，用于取消请求
  const controller = new AbortController();
  const signal = controller.signal;

  // 显示“下载中”的弹窗，并添加取消按钮
  const loading = ElLoading.service({
    text: '文件下载，请稍候...', // 弹窗内容
    spinner: 'el-icon-loading',    // 自定义加载样式
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'custom-loading-class', // 自定义样式类
    closeOnClickModal: false, // 点击遮罩不关闭
  });

  // 延迟插入取消按钮
  setTimeout(() => {
    const loadingElement = document.querySelector('.custom-loading-class .el-loading-spinner');
    if (loadingElement) {
      // 创建一个容器，包含下载进度和取消按钮
      const actionContainer = document.createElement('div');
      actionContainer.className = 'action-container';

      // 创建取消按钮
      const cancelButton = document.createElement('button');
      cancelButton.textContent = '取消下载';
      cancelButton.className = 'cancel-button'; // 样式类名，可自行定义
      cancelButton.onclick = () => {
        controller.abort(); // 取消请求
        loading.close(); // 关闭加载框
        ElMessage.warning('下载已取消');
      };

      // 添加按钮到容器中
      actionContainer.appendChild(cancelButton);

      // 插入到弹窗中
      loadingElement.appendChild(actionContainer);
    }
  }, 100);
  $http({
    method: 'get',
    url: '/files/getTaskId', // 包含文件或文件夹信息     // 只请求任务ID
    timeout: 600000 ,// 设置较长的超时时间
    signal, // 将 signal 传入请求
  }).then(response => {
    const taskId = response.data.msg; // 获取任务ID
    let downloadInProgress = false;
    file.taskId = taskId;
    $http({
      method: 'post',
      url: '/files/downLoadFile',
      data: file,  // 包含文件或文件夹信息
      responseType: 'blob' , // 获取文件流
      signal, // 将 signal 传入请求
    }).then(fileResponse => {
      const blob = fileResponse.data;
      const downloadUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = file.fileName + ".zip" || 'downloaded_file.zip';  // 设置文件名
      link.click();  // 触发下载
      URL.revokeObjectURL(downloadUrl);  // 释放内存
      ElMessage.success('文件下载成功！');
    }).catch(error => {
      console.error('下载文件失败：', error);
      ElMessage.error('文件下载失败！');
    });
    // 开始轮询任务进度
    const checkProgressInterval = setInterval(() => {
      $http({
        method: 'post',
        url: '/files/download-progress',
        data: "taskId=" + taskId,
        signal,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(Response => {
        const progress = Response.data.data;
        console.log('下载进度：', progress + '%');
        loading.setText(`下载中... ${progress}%`);

        // 当进度达到100%时
        if (progress >= 100 && !downloadInProgress) {
          clearInterval(checkProgressInterval); // 停止进度查询
          loading.close();  // 关闭加载框
          downloadInProgress = true;  // 标记下载开始
        }
      }).catch(error => {
        console.error('进度查询失败：', error);
      });
    }, 3000);  // 每1秒查询一次下载进度
  }).catch(error => {
    console.error('下载任务创建失败：', error);
    ElMessage.error('任务创建失败！');
  });
}
const downloadAFile = (file) => {
  // 创建一个 AbortController 实例，用于取消请求
  const controller = new AbortController();
  const signal = controller.signal;

  // 显示“下载中”的弹窗，并添加取消按钮
  const loading = ElLoading.service({
    text: '文件下载，请稍候...', // 弹窗内容
    spinner: 'el-icon-loading',    // 自定义加载样式
    background: 'rgba(0, 0, 0, 0.7)',
    customClass: 'custom-loading-class', // 自定义样式类
    closeOnClickModal: false, // 点击遮罩不关闭
  });

  // 延迟插入取消按钮
  setTimeout(() => {
    const loadingElement = document.querySelector('.custom-loading-class .el-loading-spinner');
    if (loadingElement) {
      // 创建一个容器，包含下载进度和取消按钮
      const actionContainer = document.createElement('div');
      actionContainer.className = 'action-container';

      // 创建取消按钮
      const cancelButton = document.createElement('button');
      cancelButton.textContent = '取消下载';
      cancelButton.className = 'cancel-button'; // 样式类名，可自行定义
      cancelButton.onclick = () => {
        controller.abort(); // 取消请求
        loading.close(); // 关闭加载框
        ElMessage.warning('下载已取消');
      };

      // 添加按钮到容器中
      actionContainer.appendChild(cancelButton);

      // 插入到弹窗中
      loadingElement.appendChild(actionContainer);
    }
  }, 100);

  $http({
    method: 'post',
    url: '/files/downLoadFile',
    data: file,
    responseType: 'blob',
    timeout: 600000, // 设置响应超时
    signal, // 将 signal 传入请求
    onDownloadProgress: (progressEvent) => {
      // 计算下载进度
      if (progressEvent.lengthComputable) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        console.log('下载进度：', percentCompleted + '%');
        loading.setText(`下载中... ${percentCompleted}%`);
      }
    }
  })
    .then(response => {
      if (response.data) {
        const blob = response.data;
        const downloadUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;

        // 设置下载的文件名   
        link.download = file.fileName || 'downloaded_file';

        // 触发下载
        link.click();

        // 释放内存
        URL.revokeObjectURL(downloadUrl);

        ElMessage.success('文件下载成功！');
      } else {
        ElMessage.error('文件下载失败！');
      }
    })
    .catch(error => {
      if (error.name === 'AbortError') {
        console.log('下载已取消');
      } else {
        console.error('下载文件时出错：', error);
        ElMessage.error('文件下载失败！');
      }
    })
    .finally(() => {
      loading.close(); // 确保关闭加载提示框
    });
};

</script>

<style lang="scss">
@import "@/assets/file.list.scss";

.file-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.file-item:hover {
  cursor: pointer; // 鼠标悬停时不变为输入指针
}

.breadcrumb a {
  cursor: pointer; // 默认点击指针
  text-decoration: none;
}

.breadcrumb a:hover {
  cursor: pointer; // 鼠标悬停时保持普通指针样式
}

.action-icons {
  display: none;
  margin-left: 10px;
}

.file-item:hover .action-icons {
  display: flex;
}

.action-icons el-button {
  margin-right: 5px;
}
/* 容器样式 */
.action-container {
  display: flex;
  justify-content: center;
  margin-top: 15px; /* 与进度条的间距 */
}

/* 按钮样式 */
.cancel-button {
  padding: 8px 20px !important;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  background-color: #f56c6c;
  border: 1px solid #f56c6c;
  border-radius: 20px; /* 圆润的边框 */
  cursor: pointer;
  transition: all 0.3s ease; /* 添加平滑过渡效果 */
  outline: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
}

.cancel-button:hover {
  background-color: #ff7b7b; /* 鼠标悬停时背景颜色 */
  border-color: #ff7b7b; /* 悬停时边框颜色 */
}

.cancel-button:active {
  background-color: #d9534f; /* 按下时背景颜色 */
  border-color: #d9534f; /* 按下时边框颜色 */
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15); /* 按下时内部阴影 */
}
</style>